<!-- 用户模块主页面 -->
<template>
  <el-container>
    <el-header class="searchHeader" height="40px">
      <el-form :model="userSearchMessage" class="searchForm">
        <el-form-item label="用户名" label-width="60px">
          <el-input v-model="userSearchMessage.name" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="工号" label-width="60px">
          <el-input v-model="userSearchMessage.code" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="电话" label-width="60px">
          <el-input v-model="userSearchMessage.tel" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="角色" label-width="60px">
          <el-select v-model="userSearchMessage.roleId" placeholder="请选择">
            <el-option :value="null">空</el-option>
            <el-option
              v-for="item in roleData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button id="btnQuery" type="primary" @click="searchUser">查询</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-container class="mainContent">
      <el-aside :width="isSubsystemShow ? '190px' : '0px'">
        <el-menu :collapse="isSubsystemShow" class="subsystemMenu">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <i class="el-icon-menu">子系统管理</i>
            </div>
            <el-tree
              :data="subsystemData"
              accordion
              @node-click="handleNodeClick"
            />
          </el-card>
        </el-menu>
      </el-aside>
      <el-main>
        <i :class="subsystemButtonStyle" style="cursor:pointer" @click="showSubsystem" />
        <el-button id="btnAdd" type="primary" icon="el-icon-plus" @click="addUser">增加</el-button>
        <el-button type="primary" icon="el-icon-copy-document" @click="beforeCopyUser">复制</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="deleteUser">删除</el-button>
        <el-dropdown split-button type="primary" style="margin: 0 10px" @command="controlStartStop">
          启停控制
          <el-dropdown-menu split-button>
            <el-dropdown-item command="ENABLE">启用</el-dropdown-item>
            <el-dropdown-item command="DISABLE">停用</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button type="primary" icon="el-icon-plus" @click="assignRole">分配角色</el-button>
        <i
          type="primary"
          icon="el-icon-plus"
          class="el-icon-menu"
          style="font-size: 30px; color: rgb(64, 158, 255); float: right;"
        />
        <DialogForm
          ref="userDialog"
          :is-dialog-form-show="isDialogFormShow"
          :operate-type="operateType"
          @closeDialog="closeDialog"
          @operateUserSuccess="operateUserSuccess"
        />
        <Table
          id="rebateSetTable"
          ref="userTable"
          @operateUserSuccess="operateUserSuccess"
          @copyUser="copyUser($event)"
          @editUser="editUser($event)"
          @viewResource="viewResource($event)"
        />
        <DialogAssignRole
          ref="roleDialog"
          :is-dialog-assign-role-show="isDialogAssignRoleShow"
          @closeDialog="closeDialog"
          @operateUserSuccess="operateUserSuccess"
        />
        <BossSoftTree
          :title="dialogAssignResourceTitle"
          :data="resourceTree"
          :type="resourceTreeType"
          :data-chosen="resourceTreeSelection"
          :visible="isDialogAssignResourceShow"
          @close="closeDialog"
          @confirm="closeDialog"
        />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {
  batchRemove,
  batchUpdate
} from '@/api/right/user'
import { treeQuery } from '@/api/right/resource'
import { mapActions, mapState } from 'vuex'
import Table from './table.vue'
import DialogForm from './dialogForm.vue'
import DialogAssignRole from './dialogAssignRole'
import BossSoftTree from '@/components/SD365UI/BossSoftTree.vue'

export default {
  name: 'User',
  components: {
    Table,
    DialogForm,
    DialogAssignRole,
    BossSoftTree
  },
  data() {
    return {
      // 是否展示子系统
      isSubsystemShow: false,
      // 子系统展示按钮图标演示
      subsystemButtonStyle: 'el-icon-arrow-right',
      // 子系统信息
      subsystemData: [],
      // 搜索时输入的用户信息
      userSearchMessage: {
        name: '',
        code: '',
        tel: '',
        roleId: '',
        positionId: '',
        departmentId: ''
      },
      // 分页信息
      paginationData: {
        // 当前页面序号，默认为1
        pageCount: 1,
        // 每页数据数
        pageSize: 10,
        // 总共数据数
        total: 0
      },
      // 增加、编辑用户信息弹窗
      isDialogFormShow: false,
      // 操作类型
      operateType: '',
      // 展示分配角色弹窗
      isDialogAssignRoleShow: false,
      // 是否展示资源分配弹窗
      isDialogAssignResourceShow: false,
      // 资源树
      resourceTree: [],
      // 被选中的资源树
      resourceTreeSelection: [],
      // 资源树类型
      resourceTreeType: 'VIEW',
      // 资源分配弹窗标题
      dialogAssignResourceTitle: ''
    }
  },
  computed: {
    /**
     * 获取角色信息
     */
    ...mapState(
      'user', [
        'roleData',
        'departmentData',
        'positionData'
      ]
    )
  },
  mounted() {
    Promise.all([
      // 获取子系统数据
      this.getRole(),
      this.getPosition(),
      this.getDepartment()
    ]).then(value => {
      // 整合子系统数据
      this.getSubsystemData()
    })
  },
  methods: {
    ...mapActions(
      'user', [
        'getDepartment',
        'getPosition',
        'getRole'
      ]
    ),
    /**
     * 增加用户数据
     */
    addUser() {
      this.operateType = 'ADD'
      this.isDialogFormShow = true
    },
    /**
     * 点击主页面复制按钮后，检验是否只选择了一条数据
     */
    beforeCopyUser() {
      if (!this.$refs.userTable.userDataSelection || this.$refs.userTable.userDataSelection.length !== 1) {
        this.$message.error('请选择一名用户复制')
        return
      }
      this.copyUser(this.$refs.userTable.userDataSelection[0])
    },
    /**
     * 复制用户数据
     * @param {*} row 用户数据
     */
    copyUser(row) {
      if (!row || row.length > 1) {
        this.$message.error('请选择一条数据')
        return
      }
      this.operateType = 'COPY'
      this.$refs.userDialog.$emit('updateUserFrom', row)
      this.isDialogFormShow = true
    },
    /**
     * 编辑用户
     * @param {*} row 用户数据
     */
    editUser(row) {
      if (!row || row.length > 1) {
        this.$message.error('请选择一条数据')
        return
      }
      this.operateType = 'EDIT'
      this.$refs.userDialog.$emit('updateUserFrom', row)
      this.isDialogFormShow = true
    },
    /**
     * 删除用户数据
     */
    deleteUser() {
      // 如果未选中用户数据，则报错
      if (!this.$refs.userTable.userDataSelection || this.$refs.userTable.userDataSelection.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }

      this.$confirm('确定要删除吗？')
        .then(res => {
        // 将数据改成接口对应的结构
          let userVOS = []
          this.$refs.userTable.userDataSelection.map((item, index) => {
            userVOS.push({ id: item.id, version: item.version })
          })
          // 调用接口
          try {
            batchRemove(userVOS).then(res => {
              if (res) {
                this.$message.success('用户删除成功')
                this.operateUserSuccess()
              } else {
                this.$message.error('用户删除失败')
              }
            })
          } catch {
            this.$message.error('网络错误')
          }
        })
        .catch(req => {})
    },
    /**
     * 查询用户
     */
    searchUser() {
      this.$refs.userTable.$emit('searchUser', this.userSearchMessage)
      this.userSearchMessage = {
        name: '',
        code: '',
        tel: '',
        roleId: '',
        positionId: '',
        departmentId: ''
      }
    },

    /**
     * 启停控制
     * @param {*} command 启用或停用
     */
    async controlStartStop(command) {
      // 若未选中数据，则退出
      if (!this.$refs.userTable.userDataSelection || this.$refs.userTable.userDataSelection.length === 0) {
        this.$message.error('至少选择一条进行启停控制')
        return
      }

      let status = 0
      // 控制是否出错
      let isError = false
      if (command === 'ENABLE') {
        status = 1
        this.$refs.userTable.userDataSelection.map(item => {
          if (item.status === 3) {
            this.$message.error('用户已经启用中')
            isError = true
            return
          }
        })
      } else if (command === 'DISABLE') {
        status = 3
        this.$refs.userTable.userDataSelection.map(item => {
          if (item.status === 0) {
            this.$message.error('用户已经停用中')
            isError = true
            return
          }
        })
      }
      if (isError) {
        return
      }

      // 将数据改为接口格式
      const userVOS = []
      this.$refs.userTable.userDataSelection.map((item, index) => {
        userVOS.push({
          id: item.id,
          status: item.status === 3 ? 0 : 3,
          version: item.version
        })
      })

      // 调用接口
      try {
        let res = await batchUpdate(userVOS)
        if (res) {
          this.$message.success('修改成功')
          this.operateUserSuccess()
        } else {
          this.$message.error('修改失败')
        }
      } catch {
        this.$message.error('网络错误')
      }
    },
    /**
     * 分配角色
     */
    assignRole() {
      // 未选择用户，报错
      if (!this.$refs.userTable.userDataSelection ||
      this.$refs.userTable.userDataSelection.length === 0) {
        this.$message.error('请至少选择一名用户进行角色分配')
        return
      }

      // 获取分页信息
      const { currentPage, pageSize, total } = this.$refs.userTable.$emit('getPaginationData')
      this.paginationData = {
        pageSize,
        total,
        pageCount: currentPage
      }

      this.isDialogAssignRoleShow = true
      this.$refs.roleDialog.$emit('getUserSelection', this.$refs.userTable.userDataSelection)
    },

    /**
     * 打开分配权限弹窗
     * @param {*} row 被选中的用户
     */
    async viewResource(row) {
      try {
        let res1 = await treeQuery({ pageSize: 1000 })
        if (!res1) {
          this.$message.error('资源获取失败')
          return
        }
        let res2 = {}
        if (row.roleList.length > 0) {
          res2 = await treeQuery({ roleId: row.roleList[0].id, pageSize: 1000 })
        }
        if (!res2) {
          this.$message.error('资源获取失败')
          return
        }

        this.resourceTree = res1.data
        this.resourceTreeSelection = res2.data
        this.resourceTreeType = 'ASSIGN'
        this.dialogAssignResourceTitle = '资源分配:'
        this.isDialogAssignResourceShow = true
      } catch {
        this.$message.error('网络错误')
      }
    },

    /**
     * 展示子系统,更改子系统按钮的图标
     */
    showSubsystem() {
      if (this.isSubsystemShow) {
        this.subsystemButtonStyle = 'el-icon-arrow-right'
        this.isSubsystemShow = false
      } else {
        this.subsystemButtonStyle = 'el-icon-arrow-left'
        this.isSubsystemShow = true
      }
    },

    /**
     * 整合子系统数据
     */
    getSubsystemData() {
      this.subsystemData[0] = { label: '部门', children: [] }
      this.departmentData.map(item => {
        this.subsystemData[0].children.push({
          label: item.name,
          id: item.id,
          type: 'department'
        })
      })
      this.subsystemData[1] = { label: '职位', children: [] }
      this.positionData.map(item => {
        this.subsystemData[1].children.push({
          label: item.name,
          id: item.id,
          type: 'position'
        })
      })
      this.subsystemData[2] = { label: '角色', children: [] }
      this.roleData.map(item => {
        this.subsystemData[2].children.push({
          label: item.name,
          id: item.id,
          type: 'role'
        })
      })
    },
    /**
     * 子系统树结点被点击
     * @param {*} node 被选中的节点
     */
    handleNodeClick(node) {
      console.log(node)
      if (!node.id) {
        return
      }

      // 重置搜索参数
      this.userSearchMessage = {
        name: '',
        code: '',
        tel: '',
        roleId: '',
        positionId: '',
        departmentId: ''
      }
      // 添加搜索参数
      if (node.type === 'department') {
        this.userSearchMessage.departmentId = node.id
      } else if (node.type === 'position') {
        this.userSearchMessage.positionId = node.id
      } else if (node.type === 'role') {
        this.userSearchMessage.roleId = node.id
      }
      this.searchUser()
    },

    /**
     * 操作用户成功
     */
    operateUserSuccess() {
      this.$refs.userTable.$emit('getUser')
    },
    /**
     * 关闭弹窗
     */
    closeDialog() {
      this.operateType = ''
      this.resourceTree = []
      this.resourceTreeSelection = []
      this.resourceTreeType = 'VIEW'
      this.dialogAssignResourceTitle = ''
      this.isDialogFormShow = false
      this.isDialogAssignRoleShow = false
      this.isDialogAssignResourceShow = false
    }
  }
}
</script>

<style scoped lang="scss">
.searchHeader{
  margin-top: 20px;
  .searchForm{
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
  }
}
.mainContent{
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  .subsystemMenu{
    margin-top: 20px;
    width: 190px;
    padding: 10px 5px;
  }
  #rebateSetTable{
    margin-top: 15px;
  }

}
</style>
